<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="预约名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入预约名称" clearable @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="预约方式" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择预约方式" clearable>
                <el-option v-for="dict in market_book_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="预约分类" prop="cateId">
              <el-select v-model="queryParams.cateId" placeholder="请选择预约分类" clearable>
                <el-option v-for="cate in cateOptions" :key="cate.id" :label="cate.name" :value="cate.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                           :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['market:book:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                       v-hasPermi="['market:book:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['market:book:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['market:book:export']">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="bookList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="主键" align="center" prop="id" v-if="false"/>
        <el-table-column label="预约名称" align="center" prop="name"/>
        <el-table-column label="预约方式" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="market_book_type" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="logo图片" align="center" prop="logoUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.logoUrl" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="预约说明" align="center" prop="description"/>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['market:book:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['market:book:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改预约列表对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="bookFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="30">
            <el-form-item label="预约名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入预约名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="30">
            <el-form-item label="门店名称" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' } as any"
                value-key="id"
                placeholder="请选择门店"
                check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!--        <el-form-item label="预约方式" prop="type">
                  <el-select v-model="form.type" placeholder="请选择预约方式，time：按时间预约；staff:按员工预约">
                    <el-option
                      v-for="dict in market_book_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>-->
        <el-row :span="30">
          <el-col>
            <el-form-item label="封面图片" prop="logo">
              <image-upload v-model="form.logo"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :span="30">
          <el-col>
            <el-form-item label="预约分类" prop="cateId">
              <el-select v-model="form.cateId" placeholder="所属分类">
                <el-option
                  v-for="cate in cateOptions"
                  :key="cate.id"
                  :label="cate.name"
                  :value="cate.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :span="30">
          <el-col>
            <el-form-item label="可预约日期" prop="dates">
              <el-date-picker
                :key="datePickerKey"
                v-model="dates"
                type="dates"
                value-format="YYYY-MM-DD"
                placeholder="选择一个或多个日期，空则表示未来7天每天都可预约"
                @change="handleDateChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :span="30">
          <el-col>
            <el-form-item label="可预约时段" prop="dates">
              <div class="add-item">
                <el-button
                  type="primary"
                  size="small"
                  icon="Plus"
                  @click="addTime"
                >添加时段
                </el-button>
              </div>
              <div class="time-item" v-for="(time, index) in times" :key="index">
                <el-time-select
                  placeholder="起始时间"
                  v-model="time.startTime"
                  :picker-options="{
        start: '00:00',
        step: '00:15',
        end: '23:45'
      }"
                  style="width: 120px"
                />
                <span style="margin: 0 8px">至</span>
                <el-time-select
                  placeholder="结束时间"
                  v-model="time.endTime"
                  :picker-options="{
        start: '00:00',
        step: '00:15',
        end: '23:45',
        minTime: time.startTime
      }"
                  style="width: 120px"
                />
                <span style="margin: 0 8px">人数上限</span>
                <el-input-number
                  v-model="time.num"
                  :min="1"
                  :max="100"
                  style="width: 120px"
                />
                <el-button
                  type="danger"
                  icon="Delete"
                  circle
                  plain
                  @click="removeTime(index)"
                  style="margin-left: 8px"
                />
              </div>

              <div class="form-tips">提示：请设置每个时段的起始时间、结束时间和可预约人数上限</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :span="30">
          <el-col>
            <el-form-item label="预约说明" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :span="30">
          <el-col>
            <el-form-item label="排序号" prop="orderNum">
              <el-input-number :min="1" :max="100" v-model="form.orderNum" placeholder="请输入排序号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :span="30">
          <el-col>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :value="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Book" lang="ts">
import {listBook, getBook, delBook, addBook, updateBook} from '@/api/market/book';
import {listBookCate} from '@/api/market/bookCate';
import {BookVO, BookQuery, BookForm, TimeRange} from '@/api/market/book/types';
import {DeptVO} from "@/api/system/dept/types";
import api from "@/api/system/user";
import {BookCateVO} from "@/api/market/bookCate/types";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {market_book_type, sys_normal_disable} = toRefs<any>(proxy?.useDict('market_book_type', 'sys_normal_disable'));

const bookList = ref<BookVO[]>([]);
const deptOptions = ref<DeptVO[]>([]);
const cateOptions = ref<BookCateVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const dates = ref<string[]>([]); // 可预约日期数组
const times = ref<TimeRange[]>([]); // 可预约时段数组
const datePickerKey = ref(0); // 用于强制重新渲染日期选择器

const queryFormRef = ref<ElFormInstance>();
const bookFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BookForm = {
  id: undefined,
  deptId: undefined,
  name: undefined,
  type: undefined,
  logo: undefined,
  goodsId: undefined,
  cateId: undefined,
  serviceDates: undefined,
  serviceTimes: undefined,
  serviceStaffIds: undefined,
  description: undefined,
  orderNum: undefined,
  status: '0',
}
const data = reactive<PageData<BookForm, BookQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    type: undefined,
    cateId: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    name: [
      {required: true, message: "预约名称不能为空", trigger: "blur"}
    ],
    cateId: [
      {required: true, message: "预约分类不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询预约列表列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBook(queryParams.value);
  bookList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

/** 查询预约分类集合 */
const getBookCateSelect = async () => {
  const res = await listBookCate();
  cateOptions.value = res.rows;
  console.log("-----" + JSON.stringify(res.rows))
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  bookFormRef.value?.resetFields();
}

// 添加时段
const addTime = () => {
  times.value.push({startTime: '', endTime: '', num: 1});
};

// 移除时段
const removeTime = (index: number) => {
  times.value.splice(index, 1);
};

// 处理日期选择变化
const handleDateChange = (selectedDates: string[]) => {
  dates.value = selectedDates;
};

// 重置日期和时段
const resetDateTime = () => {
  dates.value = [];
  times.value = [
    {startTime: '08:30', endTime: '12:00', num: 1},
    {startTime: '14:00', endTime: '18:00', num: 1}
  ];
  datePickerKey.value++; // 强制重新渲染日期选择器
};


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BookVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加预约列表";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: BookVO) => {
  reset();
  resetDateTime(); // 重置日期和时段
  const _id = row?.id || ids.value[0];
  const res = await getBook(_id);
  Object.assign(form.value, res.data);

  // 回填日期数据
  if (form.value.serviceDates) {
    dates.value = form.value.serviceDates.split(',');
    datePickerKey.value++; // 强制重新渲染日期选择器
  }

  // 回填时段数据
  if (form.value.serviceTimes) {
    try {
      times.value = JSON.parse(form.value.serviceTimes);
    } catch (e) {
      times.value = [];
    }
  }

  dialog.visible = true;
  dialog.title = "修改预约列表";
}

/** 提交按钮 */
const submitForm = () => {
  bookFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 将日期和时段数据整合到表单中
      form.value.serviceDates = dates.value.join(',');
      form.value.serviceTimes = JSON.stringify(times.value);

      buttonLoading.value = true;
      if (form.value.id) {
        await updateBook(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addBook(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BookVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除预约列表编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delBook(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('market/book/export', {
    ...queryParams.value
  }, `book_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getTreeSelect(); // 初始化部门数据
  getBookCateSelect(); //初始化预约分类
  getList();
});
</script>
<style scoped>
.time-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.add-item {
  margin-bottom: 12px;

}

.form-tips {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.el-date-editor.el-input {
  width: 100%;
}
</style>
